package com.zh.kotlin_mvvm.ui

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.core.view.ViewCompat
import androidx.lifecycle.Observer
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.initAnimation
import com.zh.common.ktx.toast
import com.zh.common.utils.LiveDataBus
import com.zh.common.utils.ZSpUtils
import com.zh.kotlin_mvvm.databinding.ActivityTestWxPayBinding

class TestWxPayActivity : BaseActivity<ActivityTestWxPayBinding>() {

    private var msgApi: IWXAPI? = null

    override fun initView(savedInstanceState: Bundle?) {
        msgApi = WXAPIFactory.createWXAPI(this, null)
        msgApi?.registerApp(viewBinding.tvAppId.text.toString())

        viewBinding.btnPay.setOnClickListener {
            wxPay(
                viewBinding.tvAppId.text.toString(),
                viewBinding.tvPartnerId.text.toString(),
                viewBinding.tvOrderPrepayId.text.toString(),
                viewBinding.tvOrderNonceStr.text.toString(),
                viewBinding.tvOrderTimeStamp.text.toString(),
                viewBinding.tvOrderSign.text.toString(),
                msgApi
            )
        }

        ZSpUtils.put("appId", viewBinding.tvAppId.text.toString())
        viewBinding.tvAppId.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                ZSpUtils.put("appId", viewBinding.tvAppId.text.toString())
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })
        initData()

        initAnimation(viewBinding.parentMy)
    }

    private fun initData() {
        /**
         * 微信支付成功回调
         */
        LiveDataBus.get().with("wx_errCode")
            .observe(this, Observer {
                when (it) {
                    0 -> "支付成功".toast()
                    -1 -> "取消失败:$it".toast()
                    -2 -> "取消支付".toast()
                }
            })
    }

    fun wxPay(
        appId: String,
        partnerId: String,
        prepayId: String,
        nonceStr: String,
        timeStamp: String,
        sign: String,
        msgApi: IWXAPI?
    ) {
        val request = PayReq()
        request.appId = appId
        request.partnerId = partnerId
        request.prepayId = prepayId
        request.packageValue = "Sign=WXPay"
        request.nonceStr = nonceStr
        request.timeStamp = timeStamp
        request.sign = sign
        msgApi?.sendReq(request)
    }
}